/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// This is the user object. Each user has a unique ID that
// allows it to be differentiated from all other clients on
// the same subscribed channel.
var user = {
uuid: null,
subscribed: false
};
 
 
// Cache frequent DOM references.
dom = {};
dom.estado0 =$("#box_estado0");
dom.estado1 =$("#box_estado1");
dom.estado2 =$("#box_estado2");
dom.estado0_Items = dom.estado0.find( "> ul" );
dom.estado1_Items = dom.estado1.find( "> ul" );
dom.estado2_Items = dom.estado2.find( "> ul" );
dom.form = $("#retrosForm" );
dom.formSprint =  dom.form.find("#sprint" );
dom.formProject = dom.form.find("#projec_id" );
dom.formCreator = dom.form.find("#cretor_id" );
dom.formMessage = dom.form.find("#retroMg" );
dom.formType = dom.form.find("#type" );
dom.formSubmit =  dom.form.find("#submitRetros" );

// Override form submit to PUSH message.
dom.form.submit(
    function( event ){
        
        // Cancel the default event.
        event.preventDefault();
        
        // Make sure there is a message to send and that the
        // user is subscribed.
             
        
        $.ajax({beforeSend:function (XMLHttpRequest) {$("#sending").fadeIn();}, 
            data:$("#submitRetros").closest("form").serialize(), 
            dataType:"html", label:"Agregar", 
            success:function (data, textStatus  )
                {$("#sending").fadeOut();
                 $("#success").html(data);
        
                }, 
            type:"post", 
            url:"\/z.palza\/cake\/\/retrospectives\/add"}); //document.location.hostname+

        // Clear and focus the current message so the
        // user can keep typing new messages.
        if ( !user.subscribed || !$("#retroMg" ).val().length ){

                // Nothing more we can do with this request.
                return;

        }

        // Send the message to the current channel.
        var select_id = document.getElementById("type");   
        sendMessageR($('#user').text() + '|'+$("#retroMg" ).val() + '|' + select_id.options[select_id.selectedIndex].value) ;
        $("#retroMg" ).val('');
        $("#retroMg" ).focus()  ;

    }
);
 
 
// I append the given message to the message log.
function appendMessageR( messageIn, isFromMe ){
    var split = messageIn.split('|');
    
    var from = split[0];
    var message = split[1];
    var type = split[2];
    // Creat the message item.
    var messageItem = document.createElement('p');

    var block = document.createElement("div");
    block.className= "bs-docs-example" ;

    
    messageItem.innerHTML = message;
    
    block.appendChild(messageItem);
    
    // Add the message element to the list.
    switch (type){
//        case "0": dom.estado0_Items.append(block);break;
//        case "1":dom.estado1_Items.append(block);break;
//        case "2":dom.estado2_Items.append(block);break;
        case "0":$("#app_estado0" ).append(block);break;
        case "1":$("#app_estado1" ).append(block);break;
        case "2":$("#app_estado2" ).append(block);break;
    }
    
 
}
 
 
// I send the given message to all subscribed clients.
function sendMessageR( message ){
 
    // Immediately add the message to the UI so the user
    // feels like the interface is super responsive.
    appendMessageR( message, true );

    // Push the message to PubNub. Attach the user UUID as
    // part of the message so we can filter it out when it
    // gets echoed back (as part of our subscription).
    PUBNUB.publish({
        channel: 'retrospectiveREAL_'+$('#idProject').text(),
        message: {
            uuid: user.uuid,
            message: message
        }
    });
 
};
 
 
// I receive the message on the current channel.
function receiveMessageR( message ){
 
    // Check to make sure the message is not just being
    // echoed back.
    if (message.uuid === user.uuid){

        // This message has already been handled locally.
        return;

    }

    // Add the message to the chat log.
    appendMessageR( message.message );
 
}
 
 
// -------------------------------------------------- //
// -------------------------------------------------- //
 
 
// In order to initialize the system, we have to wait for the
// client to receive a UUID and for the subscription to the
// PubNub server to be established.
var initR = $.when(
 
    // Get the user ID.
    getUUID(),

    // Subscribe to the PubNub channel.
    $.Deferred(
        function( deferred ){

            // When the PubNub connection has been
            // established, resolve the deferred container.
            PUBNUB.subscribe({
            channel:'retrospectiveREAL_'+$('#idProject').text(),
            callback: receiveMessageR,
            connect: deferred.resolve,
            error: deferred.fail
            });

        }
    )
 
);
 
// When the UUID has come back, prepare the user for use
// within the system.
initR.done(
    function( uuid ){

        // Store the UUID with the user.
        user.uuid = uuid;

        // Flag the user as subscribed.
        user.subscribed = true;

        // Enable the message form.
        dom.formSubmit.removeAttr( "disabled" );

    }
);
 
 
// -------------------------------------------------- //
// -------------------------------------------------- //
// -------------------------------------------------- //
// -------------------------------------------------- //
 
 
// NOTE: The following are just PubNub utility methods that
// have been converted from callback-based responses to
// deferred-based promises.
 
 
// I get a UUID from the PUBNUB server. I return a promise
// of the value to be returned.
function getUUID(){

    // Since the core UUID method uses a callback, we need to
    // create our own intermediary deferred object to wire
    // the two workflows together.
    var deferred = $.Deferred();

    // Ask PubNub for a UUID.
    PUBNUB.uuid(
        function( uuid ){

            // Resolve the uuid promise.
            deferred.resolve( uuid );

        }
    );

    // Return the UUID promise.
    return( deferred.promise() );
 
}
 

